using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Reflection;
using System.Data.Common;

using Pampa.Grid.Data;

namespace Pampa.Grid.Core.Filters
{
    public abstract class Filter
    {
        protected string source;
        protected GroupFilter parent;
        protected bool persistable;

        protected Filter()
        {
            persistable = true;
        }

        #region Properties

        internal virtual string Source
        {
            get { return source; }
            set { source = value; }
        }

        public virtual GroupFilter Parent
        {
            get { return parent; }
            set { parent = value; }
        }

        public virtual bool Persistable
        {
            get { return persistable; }
            set { persistable = value; }
        }

        #endregion

        #region Xml

        public static Filter FromXml(XmlNode node)
        {
            Assembly assembly = Assembly.GetAssembly(typeof(Filter));
            
            string nodeName;

            switch(node.Name)
            {
                case "simplefilter":
                    nodeName = "SimpleFilter";
                    break;
                case "andgroupfilter":
                    nodeName = "AndGroupFilter";
                    break;
                case "orgroupfilter":
                    nodeName = "OrGroupFilter";
                    break;
                default:
                    nodeName = node.Name;
                    break;
            }

            Filter filter = (Filter)assembly.CreateInstance("Pampa.Grid.Core.Filters." + nodeName);
            filter.LoadXml(node);

            return filter;
        }

        public void ToXml(ref XmlNode root)
        {
            XmlDocument document = root.OwnerDocument;
            XmlNode node = document.CreateElement(this.GetType().Name);
            root.AppendChild(node);

            this.BuildNode(ref node);
        }

        #endregion

        protected abstract void LoadXml(XmlNode node);

        protected abstract void BuildNode(ref XmlNode node);
    }

}
